import React,{useState,useEffect} from 'react'
import * as action from "../../action"
import { ProductCard, Tag, Button } from 'react-vant';
import {useDispatch,useSelector} from "react-redux"
import { SubmitBar } from 'react-vant';
import { Empty } from 'react-vant';
function Shocar() {
  let [sum,setSum] = useState(0) // 总价
  let [count,setCount] = useState(0) // 总个数
  let dispatch = useDispatch()
  let store = useSelector((state)=>{
      return {
        ...state.shopcarreducer
      }
  })
  let addfn = (id)=>{
      // 
      dispatch(action.addFn(id))
  }
  let delfn = (id)=>{
    dispatch(action.delFn(id))
  }
  let checkitem = (id)=>{
    dispatch(action.checkItem(id))
  }
  let delete1 = (id)=>{
    dispatch(action.delete1fn(id))
  }
  let checkAllfn = ()=>{
    dispatch(action.checkallfn())
  }
  
  useEffect(()=>{
    let checkarr = store.shoparr.filter(item=>item.flag)
    console.log(checkarr,1234567);
    let newsum = checkarr.reduce((a,b)=>{
      return a + b.price * b.num
    },0)
    let newcount = checkarr.reduce((a,b)=>{
      return a +  b.num
    },0)
    setCount(newcount)
    setSum(newsum)
  },[store.shoparr])
  console.log(store);
  return (
    <div>
      <h4> 全选： <input type="checkbox" checked={store.checkall} onChange={checkAllfn} /></h4>
    
      {
        store.shoparr &&   store.shoparr.length ?  store.shoparr.map((item,index)=>{
          return <ProductCard
          key={index}
          num={item.num}
          price={item.price}
          desc={item.des}
          title={item.tit}
          thumb={item.img}
          footer={
            <>
              <input type="checkbox" checked={item.flag} onChange={()=>{checkitem(item.id)}} />
              <Button size="small" round plain style={{ marginRight: 2 }} onClick={()=>delfn(item.id)}>
                -
              </Button>
              <Button size="small" round plain onClick={()=>addfn(item.id)}>
                +
              </Button>
              <Button onClick={()=>delete1(item.id)}>删除</Button>
            </>
          }
        />

        }):<Empty description="请添加一条到购物车" />
      }
      <div className="demo-submit-bar"><SubmitBar price={sum * 100} buttonText="提交订单" tip={
        <>
          你选中的商品个数是<span style={{ color: 'red' }}>{count}个</span>
        </>
      } /></div>
    </div>
  )
}

export default Shocar